package com.example.service;

import com.example.api.PostApi;
import com.example.entity.Post;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;
import java.util.List;

/**
 * 文章服务类
 * 演示文章相关的 API 调用
 * 
 * @author example
 * @since 2024-01-01
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PostService {

    private final PostApi postApi;

    /**
     * 获取所有文章
     */
    public List<Post> getAllPosts() {
        try {
            Call<List<Post>> call = postApi.getPosts();
            Response<List<Post>> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("成功获取文章列表，数量: {}", response.body().size());
                return response.body();
            } else {
                log.error("获取文章列表失败，状态码: {}", response.code());
                return List.of();
            }
        } catch (IOException e) {
            log.error("获取文章列表异常", e);
            return List.of();
        }
    }

    /**
     * 根据 ID 获取文章
     */
    public Post getPostById(Long id) {
        try {
            Call<Post> call = postApi.getPost(id);
            Response<Post> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("成功获取文章信息: {}", response.body().getTitle());
                return response.body();
            } else {
                log.error("获取文章信息失败，文章ID: {}, 状态码: {}", id, response.code());
                return null;
            }
        } catch (IOException e) {
            log.error("获取文章信息异常，文章ID: {}", id, e);
            return null;
        }
    }

    /**
     * 根据用户 ID 获取文章列表
     */
    public List<Post> getPostsByUser(Long userId) {
        try {
            Call<List<Post>> call = postApi.getPostsByUser(userId);
            Response<List<Post>> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("成功获取用户文章列表，用户ID: {}, 数量: {}", userId, response.body().size());
                return response.body();
            } else {
                log.error("获取用户文章列表失败，用户ID: {}, 状态码: {}", userId, response.code());
                return List.of();
            }
        } catch (IOException e) {
            log.error("获取用户文章列表异常，用户ID: {}", userId, e);
            return List.of();
        }
    }

    /**
     * 创建文章
     */
    public Post createPost(Post post) {
        try {
            Call<Post> call = postApi.createPost(post);
            Response<Post> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("成功创建文章: {}", response.body().getTitle());
                return response.body();
            } else {
                log.error("创建文章失败，状态码: {}", response.code());
                return null;
            }
        } catch (IOException e) {
            log.error("创建文章异常", e);
            return null;
        }
    }

    /**
     * 使用表单方式创建文章
     */
    public Post createPostWithForm(Long userId, String title, String body) {
        try {
            Call<Post> call = postApi.createPostWithForm(userId, title, body);
            Response<Post> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("成功使用表单创建文章: {}", response.body().getTitle());
                return response.body();
            } else {
                log.error("使用表单创建文章失败，状态码: {}", response.code());
                return null;
            }
        } catch (IOException e) {
            log.error("使用表单创建文章异常", e);
            return null;
        }
    }

    /**
     * 更新文章
     */
    public Post updatePost(Long id, Post post) {
        try {
            Call<Post> call = postApi.updatePost(id, post);
            Response<Post> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("成功更新文章: {}", response.body().getTitle());
                return response.body();
            } else {
                log.error("更新文章失败，文章ID: {}, 状态码: {}", id, response.code());
                return null;
            }
        } catch (IOException e) {
            log.error("更新文章异常，文章ID: {}", id, e);
            return null;
        }
    }

    /**
     * 删除文章
     */
    public boolean deletePost(Long id) {
        try {
            Call<Void> call = postApi.deletePost(id);
            Response<Void> response = call.execute();
            
            if (response.isSuccessful()) {
                log.info("成功删除文章，文章ID: {}", id);
                return true;
            } else {
                log.error("删除文章失败，文章ID: {}, 状态码: {}", id, response.code());
                return false;
            }
        } catch (IOException e) {
            log.error("删除文章异常，文章ID: {}", id, e);
            return false;
        }
    }

    /**
     * 文件上传示例
     * 注意：这是一个示例方法，实际的 JSONPlaceholder API 不支持文件上传
     */
    public String uploadFile(MultipartFile file) {
        try {
            // 创建 RequestBody
            RequestBody requestBody = RequestBody.create(
                    MediaType.parse(file.getContentType()), 
                    file.getBytes()
            );
            
            // 创建 MultipartBody.Part
            MultipartBody.Part filePart = MultipartBody.Part.createFormData(
                    "file", 
                    file.getOriginalFilename(), 
                    requestBody
            );
            
            Call<ResponseBody> call = postApi.uploadFile(filePart);
            Response<ResponseBody> response = call.execute();
            
            if (response.isSuccessful()) {
                String result = response.body().string();
                log.info("文件上传成功: {}", file.getOriginalFilename());
                return result;
            } else {
                log.error("文件上传失败，状态码: {}", response.code());
                return null;
            }
        } catch (IOException e) {
            log.error("文件上传异常", e);
            return null;
        }
    }

    /**
     * 多文件上传示例
     */
    public String uploadMultipleFiles(String description, List<MultipartFile> files) {
        try {
            // 创建文件部分列表
            List<MultipartBody.Part> fileParts = files.stream()
                    .map(file -> {
                        try {
                            RequestBody requestBody = RequestBody.create(
                                    MediaType.parse(file.getContentType()), 
                                    file.getBytes()
                            );
                            return MultipartBody.Part.createFormData(
                                    "files", 
                                    file.getOriginalFilename(), 
                                    requestBody
                            );
                        } catch (IOException e) {
                            log.error("处理文件异常: {}", file.getOriginalFilename(), e);
                            return null;
                        }
                    })
                    .filter(part -> part != null)
                    .toList();
            
            Call<ResponseBody> call = postApi.uploadMultipleFiles(description, fileParts);
            Response<ResponseBody> response = call.execute();
            
            if (response.isSuccessful()) {
                String result = response.body().string();
                log.info("多文件上传成功，文件数量: {}", files.size());
                return result;
            } else {
                log.error("多文件上传失败，状态码: {}", response.code());
                return null;
            }
        } catch (IOException e) {
            log.error("多文件上传异常", e);
            return null;
        }
    }

    /**
     * 演示文章相关功能
     */
    public void demonstratePostFeatures() {
        log.info("=== 演示文章功能 ===");
        
        // 1. 获取所有文章
        List<Post> allPosts = getAllPosts();
        if (!allPosts.isEmpty()) {
            log.info("获取到 {} 篇文章", allPosts.size());
        }
        
        // 2. 获取特定用户的文章
        List<Post> userPosts = getPostsByUser(1L);
        if (!userPosts.isEmpty()) {
            log.info("用户 1 有 {} 篇文章", userPosts.size());
        }
        
        // 3. 创建新文章
        Post newPost = new Post();
        newPost.setUserId(1L);
        newPost.setTitle("测试文章标题");
        newPost.setBody("这是一篇测试文章的内容");
        
        Post createdPost = createPost(newPost);
        if (createdPost != null) {
            log.info("创建文章成功，ID: {}", createdPost.getId());
        }
        
        // 4. 使用表单方式创建文章
        Post formPost = createPostWithForm(1L, "表单创建的文章", "这是通过表单创建的文章内容");
        if (formPost != null) {
            log.info("表单创建文章成功，ID: {}", formPost.getId());
        }
        
        log.info("=== 文章功能演示完成 ===");
    }
} 